package com.feidee.data.report.util;

import com.feidee.data.report.constant.Constant;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.params.ClientPNames;
import org.apache.http.conn.routing.HttpRoute;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.PoolingClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.params.CoreProtocolPNames;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class HttpConnectionManager {

	private static Logger logger = Logger.getLogger(HttpConnectionManager.class);

	/**
	 * 连接池里的最大连接数
	 */
	public static final int MAX_TOTAL_CONNECTIONS = 200;

	/**
	 * 每个路由的默认最大连接数
	 */
	public static final int MAX_ROUTE_CONNECTIONS = 200;

	/**
	 * 连接超时时间
	 */
	public static final int CONNECT_TIMEOUT = 50000;

	/**
	 * 套接字超时时间
	 */
	public static final int SOCKET_TIMEOUT = 50000;

	/**
	 * 连接池中 连接请求执行被阻塞的超时时间
	 */
	public static final long CONN_MANAGER_TIMEOUT = 60000 * 60L;

	/**
	 * http连接相关参数
	 */
	private static HttpParams parentParams;

	/**
	 * http线程池管理器
	 */
	private static PoolingClientConnectionManager cm;

	/**
	 * http客户端
	 */
	private static DefaultHttpClient httpClient;

	/**
	 * 默认目标主机
	 */
	private static final HttpHost DEFAULT_TARGETHOST = new HttpHost(Constant.TASK_RES_RETURN_URI, 80);

	/**
	 * 初始化http连接池，设置参数、
	 */
	static {
		SchemeRegistry schemeRegistry = new SchemeRegistry();
		schemeRegistry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory()));
		schemeRegistry.register(new Scheme("https", 443, SSLSocketFactory.getSocketFactory()));

		cm = new PoolingClientConnectionManager(schemeRegistry);
		cm.setMaxTotal(MAX_TOTAL_CONNECTIONS);
		cm.setDefaultMaxPerRoute(MAX_ROUTE_CONNECTIONS);
		cm.setMaxPerRoute(new HttpRoute(DEFAULT_TARGETHOST), 100); // 设置对目标主机的最大连接数

		parentParams = new BasicHttpParams();
		parentParams.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
		parentParams.setParameter(ClientPNames.DEFAULT_HOST, DEFAULT_TARGETHOST); // 设置默认targetHost
		parentParams.setParameter(ClientPNames.CONN_MANAGER_TIMEOUT, CONN_MANAGER_TIMEOUT);
		parentParams.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, CONNECT_TIMEOUT);
		parentParams.setParameter(CoreConnectionPNames.SO_TIMEOUT, SOCKET_TIMEOUT);
		parentParams.setParameter(ClientPNames.ALLOW_CIRCULAR_REDIRECTS, true);
		parentParams.setParameter(ClientPNames.HANDLE_REDIRECTS, true);
	}

	public static HttpParams getParentParams() {
		return parentParams;
	}

	public static void setParentParams(HttpParams parentParams) {
		HttpConnectionManager.parentParams = parentParams;
	}

	public static PoolingClientConnectionManager getCm() {
		return cm;
	}

	public static void setCm(PoolingClientConnectionManager cm) {
		HttpConnectionManager.cm = cm;
	}

	@SuppressWarnings("deprecation")
	public static void sendPOST(String uri, Map<String, String> map) {
		HttpPost httppost = new HttpPost(uri);
		try {
			List<NameValuePair> nvps = new ArrayList<NameValuePair>();
			for (String name : map.keySet()) {
				nvps.add(new BasicNameValuePair(name, map.get(name)));
			}
			httppost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
			httpClient = new DefaultHttpClient(cm, parentParams);
			HttpResponse sendRes = httpClient.execute(httppost);
			logger.info("前端异步返回结果: " + EntityUtils.toString(sendRes.getEntity()));
		} catch (Exception e) {
			logger.error("异步返回结果发送异常:", e);
		} finally {
			httppost.releaseConnection();
		}
	}

	public static void sendGET(String uri, Map<String, String> map) throws Exception {
		try {
			httpClient = new DefaultHttpClient(cm, parentParams);
			StringBuffer url = new StringBuffer(uri);
			for (String name : map.keySet()) {
				url.append("?").append(name).append(map.get(name)).append("&");
			}
			HttpGet httpGet = new HttpGet(url.toString());
			httpClient.execute(httpGet);
			httpGet.releaseConnection();
		} catch (Exception e) {
			e.printStackTrace();
			throw new Exception(e.getMessage(), e);
		}
	}

}